﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DAO;
namespace Sklad.WindowsApplication
{
    public partial class AddSendingForm : Form
    {
        public static List<TempClass> itemlist;
        public static BindingSource bs = new BindingSource();

        public AddSendingForm()
        {
            InitializeComponent();
            itemlist = new List<TempClass>();
            this.cb_rec_empl.Items.AddRange(AdminMainForm.dr.EmployeeRepository.GetAll().ToArray());
            this.cb_client.Items.AddRange(AdminMainForm.dr.ClientRepository.GetAll().ToArray());
            UpdateDataGrid();
            this.dataGridView1.DataSource = bs;
            this.dataGridView1.Columns[0].Visible = false;
            this.dataGridView1.Columns[1].Visible = false;
        }

        private void UpdateDataGrid()
        {
            int cnt = 0;
            foreach (var item in itemlist)
            {
                item.local_id = cnt++;
            }
            bs.DataSource = new BindingList<TempClass>(itemlist);
        }

        private void bt_add_product_Click(object sender, EventArgs e)
        {
            AddProductToForm aptf = new AddProductToForm(FormType.AddSendingForm);
            aptf.Visible = true;
            aptf.FormClosing += aptf_FormClosing;
            this.Visible = false;
        }

        private void aptf_FormClosing(object sender, FormClosingEventArgs e)
        {
            UpdateDataGrid();
            this.Visible = true;
        }

        private void bt_delete_product_Click(object sender, EventArgs e)
        {
            var temp = bs.Current as TempClass;
            itemlist.RemoveAll(x => x.local_id == temp.local_id);
            UpdateDataGrid();
        }

        private void bt_add_Click(object sender, EventArgs e)
        {
            int idEmpl = (this.cb_rec_empl.SelectedItem as Employer).Id;
            int idCli = (this.cb_client.SelectedItem as Client).Id;
            DateTime dt = DateTime.Parse(this.dp_receive.Text);
            AdminMainForm.dr.ExtraditionRepository.Add(new Extradition()
            {
                Id_Employer = idEmpl,
                Id_Client = idCli,
                Date = dt
            });

            var last = AdminMainForm.dr.ExtraditionRepository.GetAll().Last();

            foreach (var item in itemlist)
            {
                AdminMainForm.dr.ExtraditionProductRep.Add(
                       new Extradition_Product()
                       {
                           Id_Extradition = last.Id,
                           Id_Product = item.Id,
                           Count = item.Count
                       });
            }
            this.Close();
        }
    }
}
